from . import reactor
from .deferred import Deferred


class Stream(object):
    MAX_IO_CHUNK = 8000
    
    def fileno(self):
        raise NotImplementedError
    def _write(self):
        raise NotImplementedError
    def _read(self, count):
        raise NotImplementedError
    
    def _on_read(self):
        if self._closed:
            self.disconnected()
            return False
        data = self._read()
        if not data:
            #self.close()
            self.disconnected()
            return False
        else:
            self.received(data)
            return True
    
    def read(self, count):
        dfr = Deferred()
        def _on_read(self = self, dfr = dfr, count = count):
            data = self._read(count)
            dfr.set(False, data)
        return dfr
    
    def _on_write(self):
        if self._write_buf:
            self._write()
        return bool(self._write_buf)
    def write(self, data):
        if self._closed:
            raise StreamClosed
        if not self._write_buf:
            reactor.register_write(self.file, self._can_write)
        self._write_buf += data




